package com.lbiuse.cwc.wechat.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lbiuse.utils.propertyUtils.WxConfigUtils;
import com.lbiuse.wx.AccountCache;
import com.lbiuse.wx.api.WeChatAPI;
import com.lbiuse.wx.bean.Account;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("wx/accessToken")
public class AccessTokenController {

	WeChatAPI api = WeChatAPI.getAPI(WxConfigUtils.getAppId());

	@RequestMapping
	public void get(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String appId = request.getParameter("appid");
		String secret = request.getParameter("secret");
		if (appId == null || secret == null) {
			response.setStatus(404);
			return;
		}
		Account account = AccountCache.get(appId);
		if (account != null && secret.equals(account.getAppSecret())) {
			String tempalte = "{\"access_token\":\"%s\",\"expires_in\":7200}";
			response.getWriter().write(
					String.format(tempalte, api.getAccessToken()));
		} else {
			response.setStatus(404);
		}

	}
}
